package com.kwdb.importtool.config;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 数据库配置类
 * 用于加载和管理KWDB和MySQL的连接配置
 */
@Data
public class DatabaseConfig {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);

    // KWDB连接配置
    private String kwdbUrl;
    private String kwdbUsername;
    private String kwdbPassword;
    private String kwdbDriver;

    // MySQL连接配置（用于验证或对比）
    private String mysqlUrl;
    private String mysqlUsername;
    private String mysqlPassword;
    private String mysqlDriver;

    // 连接池配置
    private int maxPoolSize;
    private int connectionTimeout;
    private int idleTimeout;

    // 迁移配置
    private int batchSize;
    private boolean skipErrors;
    private boolean validateData;

    private static final String DEFAULT_CONFIG_FILE = "application.conf";

    public DatabaseConfig() {
        loadDefaultConfig();
    }

    public DatabaseConfig(String configFilePath) {
        loadConfigFromFile(configFilePath);
    }

    /**
     * 从默认配置文件加载配置
     */
    private void loadDefaultConfig() {
        try {
            Config config = ConfigFactory.load(DEFAULT_CONFIG_FILE);
            loadConfig(config);
            logger.info("Loaded database configuration from default config file");
        } catch (Exception e) {
            logger.warn("Failed to load default config file, using default values", e);
            setDefaultValues();
        }
    }

    /**
     * 从指定文件加载配置
     */
    private void loadConfigFromFile(String configFilePath) {
        try {
            File configFile = new File(configFilePath);
            if (configFile.exists()) {
                Config config = ConfigFactory.parseFile(configFile);
                loadConfig(config);
                logger.info("Loaded database configuration from: {}", configFilePath);
            } else {
                logger.warn("Config file not found: {}, using default config", configFilePath);
                loadDefaultConfig();
            }
        } catch (Exception e) {
            logger.error("Error loading config file: {}", configFilePath, e);
            loadDefaultConfig();
        }
    }

    /**
     * 从Config对象加载配置
     */
    private void loadConfig(Config config) {
        // KWDB配置
/*        this.kwdbUrl = config.getString("kwdb.url");
        this.kwdbUsername = config.getString("kwdb.username");
        this.kwdbPassword = config.getString("kwdb.password");
        this.kwdbDriver = config.getString("kwdb.driver");*/

        // MySQL配置
/*
        this.mysqlUrl = config.getString("mysql.url");
        this.mysqlUsername = config.getString("mysql.username");
        this.mysqlPassword = config.getString("mysql.password");
        this.mysqlDriver = config.getString("mysql.driver");
*/

        // 连接池配置
/*        this.maxPoolSize = config.getInt("connection.pool.max-size");
        this.connectionTimeout = config.getInt("connection.pool.timeout");
        this.idleTimeout = config.getInt("connection.pool.idle-timeout");*/

        // 迁移配置
/*        this.batchSize = config.getInt("migration.batch-size");
        this.skipErrors = config.getBoolean("migration.skip-errors");
        this.validateData = config.getBoolean("migration.validate-data");*/
    }

    /**
     * 设置默认值
     */
    private void setDefaultValues() {
        // KWDB默认配置
        this.kwdbUrl = "jdbc:kaiwudb://localhost:8123/default";
        this.kwdbUsername = "admin";
        this.kwdbPassword = "admin";
        this.kwdbDriver = "com.kaiwudb.Driver";

        // MySQL默认配置
        this.mysqlUrl = "jdbc:mysql://localhost:3306/mysql";
        this.mysqlUsername = "root";
        this.mysqlPassword = "root";
        this.mysqlDriver = "com.mysql.cj.jdbc.Driver";

        // 连接池默认配置
        this.maxPoolSize = 10;
        this.connectionTimeout = 30000;
        this.idleTimeout = 600000;

        // 迁移默认配置
        this.batchSize = 1000;
        this.skipErrors = false;
        this.validateData = true;
    }

    /**
     * 验证配置是否有效
     */
    public boolean isValid() {
        if (kwdbUrl == null || kwdbUrl.trim().isEmpty()) {
            logger.error("KWDB URL is required");
            return false;
        }
        if (kwdbUsername == null || kwdbUsername.trim().isEmpty()) {
            logger.error("KWDB username is required");
            return false;
        }
        // 密码可以为空（某些数据库允许空密码）

        return true;
    }

    /**
     * 验证KWDB配置是否有效
     */
    public boolean isKwdbConfigValid() {
        return kwdbUrl != null && !kwdbUrl.trim().isEmpty() &&
                kwdbUsername != null && !kwdbUsername.trim().isEmpty();
    }

    /**
     * 验证MySQL配置是否有效
     */
    public boolean isMysqlConfigValid() {
        return mysqlUrl != null && !mysqlUrl.trim().isEmpty() &&
                mysqlUsername != null && !mysqlUsername.trim().isEmpty();
    }

    // Getter和Setter方法
    public String getKwdbUrl() {
        return kwdbUrl;
    }

    public void setKwdbUrl(String kwdbUrl) {
        this.kwdbUrl = kwdbUrl;
    }

    public String getKwdbUsername() {
        return kwdbUsername;
    }

    public void setKwdbUsername(String kwdbUsername) {
        this.kwdbUsername = kwdbUsername;
    }

    public String getKwdbPassword() {
        return kwdbPassword;
    }

    public void setKwdbPassword(String kwdbPassword) {
        this.kwdbPassword = kwdbPassword;
    }

    public String getKwdbDriver() {
        return kwdbDriver;
    }

    public void setKwdbDriver(String kwdbDriver) {
        this.kwdbDriver = kwdbDriver;
    }

    public String getMysqlUrl() {
        return mysqlUrl;
    }

    public void setMysqlUrl(String mysqlUrl) {
        this.mysqlUrl = mysqlUrl;
    }

    public String getMysqlUsername() {
        return mysqlUsername;
    }

    public void setMysqlUsername(String mysqlUsername) {
        this.mysqlUsername = mysqlUsername;
    }

    public String getMysqlPassword() {
        return mysqlPassword;
    }

    public void setMysqlPassword(String mysqlPassword) {
        this.mysqlPassword = mysqlPassword;
    }

    public String getMysqlDriver() {
        return mysqlDriver;
    }

    public void setMysqlDriver(String mysqlDriver) {
        this.mysqlDriver = mysqlDriver;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public int getIdleTimeout() {
        return idleTimeout;
    }

    public void setIdleTimeout(int idleTimeout) {
        this.idleTimeout = idleTimeout;
    }

    public int getBatchSize() {
        return batchSize;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public boolean isSkipErrors() {
        return skipErrors;
    }

    public void setSkipErrors(boolean skipErrors) {
        this.skipErrors = skipErrors;
    }

    public boolean isValidateData() {
        return validateData;
    }

    public void setValidateData(boolean validateData) {
        this.validateData = validateData;
    }

    @Override
    public String toString() {
        return "DatabaseConfig{" +
                "kwdbUrl='" + kwdbUrl + '\'' +
                ", kwdbUsername='" + kwdbUsername + '\'' +
                ", kwdbPassword='***'" +
                ", mysqlUrl='" + mysqlUrl + '\'' +
                ", mysqlUsername='" + mysqlUsername + '\'' +
                ", mysqlPassword='***'" +
                ", batchSize=" + batchSize +
                ", skipErrors=" + skipErrors +
                ", validateData=" + validateData +
                '}';
    }
}